﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Linq;
using System.Xml.Linq;
using System.Diagnostics;
using System.Threading.Tasks;

namespace UPnP
{
    public class Device
    {
        XElement Dom;
        Uri BaseUri;
        const string NS = "urn:schemas-upnp-org:device-1-0";

        private Device(string uri, XElement dom)
        {
            this.Dom = dom;
            this.BaseUri = new Uri(uri, UriKind.Absolute);
        }

        public string FriendlyName
        {
            get
            {
                return (string)Dom.Descendants(XName.Get("friendlyName", NS)).FirstOrDefault();
            }
        }

        public string FindService(string urn)
        {
            var service = from item in Dom.Descendants(XName.Get("service", NS))
                          where (string)item.Element(XName.Get("serviceId", NS)) == urn
                          select new
                          {
                              ServiceType = (string)item.Element(XName.Get("serviceType", NS)),
                              ServiceId = (string)item.Element(XName.Get("serviceId", NS)),
                              SCP = (string)item.Element(XName.Get("SCPDURL", NS)),
                              ControlURL = (string)item.Element(XName.Get("controlURL", NS))
                          };

            // The SCP is relative to the base uri
            return service != null ? BaseUri.GetComponents(UriComponents.SchemeAndServer, UriFormat.Unescaped) + service.First().ControlURL : null;
        }

        internal static void WTFLinq(XElement dom)
        {
            var all = from item in dom.Descendants()
                      select new
                      {
                          item.Name,
                          item.Value
                      };
            foreach (var x in all)
                Debug.WriteLine(x.Name + "=" + x.Value);
        }

        public static async Task<Device> Create_Async(string uri)
        {
            var xml = await new WebClient().DownloadStringTaskAsync(uri);
            var dom = XElement.Parse(xml);
            if (dom.GetDefaultNamespace() != "urn:schemas-upnp-org:device-1-0")
            {
                Debug.WriteLine("Bad default namespace " + dom.GetDefaultNamespace());
                return null;
            }

            Device device = new Device(uri, dom);
            return device;
        }
    }

}
